package com.tianpengtech.admin.role;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.tianpengtech.admin.AbstractAdmin;
import com.tianpengtech.admin.AbstractAdminController;
import com.tianpengtech.admin.InitInterceptor;
import com.tianpengtech.admin.permission.PermissionDao;
import com.tianpengtech.common.GlobalConfigConstant;
import com.tianpengtech.common.exception.ValidateException;
import com.tianpengtech.common.model.dictionary.Dictionary;
import com.tianpengtech.common.model.permission.Permission;
import com.tianpengtech.common.model.role.Role;
import com.tianpengtech.common.util.JsonUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;

import java.util.ArrayList;
import java.util.List;

/**
* 路由配置地址：add("/admin/role", RoleAdminController.class, "/admin/role");
* 数据库映射地址：arp.addMapping(Role.dao.tableName(),Role.class);
*/
@Before(InitInterceptor.class)
@RequiresAuthentication
public class RoleAdminController extends AbstractAdminController{

	@Override
	protected void config() {
		this.clazz=Role.class;
		this.service=new RoleAdminServiceImpl();
	}

	@Override
	public void beforeAdd() {

	}

	@Override
	public void beforeAdd(Model< ? > model) throws ValidateException {

	}

	@Override
	public void beforeQueryById(Model<?> model, int id) {

	}

	@Override
	public void beforeUpdate(Model< ? > model) throws ValidateException {

	}

	@Override
	public void beforeDelete(Model< ? > model) {

	}


	public void dispatch(){

		int id = getParaToInt(Role.ID,GlobalConfigConstant.DEFAULT_VALUE_ZERO);
		Model<Role> roleModel = getModel(Role.class);
				String sql="select * from "+Dictionary.dao.tableName()+" where pid=? order by id desc";

		List<Dictionary> dictionaryList = Dictionary.dao.find(sql,Dictionary.CONST_PERMISSION_CODE);

		for(Dictionary d:dictionaryList){
			d.put("modulePermission", PermissionDao.ME.queryPermissionByRefId(d.getLong(Dictionary.ID)));
		}
		setAttr("moduleList",dictionaryList);
		Role role = (Role)this.service.queryById(roleModel, id);
		setAttr("role", role);
		setAttr("rolePermission",PermissionDao.ME.queryUniquePermissionByRole(role.getStr(Role.CODE)));
		renderTemplate("role-dispatch.html");
	}

	@Before(POST.class)
	public void roleDispatch(){
		try {
			String defaultJson="{\"role\":\"\",\"permissions\":[]}";//默认JSON
			String permission  = getPara("permission",defaultJson);
			IRoleDispatch dispatch = new RoleDispatchImpl();
			dispatch.roleDispatch(permission);
			renderJson(JsonUtil.printSuccess("分配成功"));
		} catch (ValidateException e) {
			renderJson(JsonUtil.printError(e.getMessage()));
		}
	}

	@Override
	public void parsePageRecord(Object o) {
		
	}
}

	